package controllers;

import helpers.CrawlerHelper;
import helpers.FileHelper;
import helpers.UrlHelper;

import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import systems.CurrentDomain;

import debugs.DnsDebug;

import entities.Dns;

public class DnsServlet extends HttpServlet{
	
	private static final Logger log = Logger.getLogger(DnsServlet.class.getName());
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		log.setLevel(Level.FINE);
		
		String update = (String) request.getParameter("u");
		
		TreeMap<String, String> check = new TreeMap<String, String>();
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String name = URLDecoder.decode(path.toLowerCase().replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		String keywords = name + ", dns lookup, name server lookup, name server, dns, dns information, dns info, soa records, dns server, dns record";
		String description = "Dns information for domain " + name + ": information about name server, email, serial number, maximum, refresh, name server, dns records ...";
		
		//Convert to main domain
		Dns dns = new Dns();
		
		if (name != null && !name.isEmpty()) {
			name = UrlHelper.getMainDomain(name);
			System.out.println(name);
			if (!UrlHelper.checkDomain(name)) {
				check.put("name", name + " is not a domain. Please enter again!");
			}
			if (check.size() == 0) {
				//Check domain exists db
				dns = FileHelper.getDnsByFileName(name);
				
				if (dns == null || update != null) {
					if (dns == null) 
						dns = new Dns();
					dns.setDomain(name);
					dns.setUpdated(new Date());
					dns = CrawlerHelper.getDns(dns);
					if (!dns.getDnsRecord().isEmpty()) {
						FileHelper.savePage(dns);
					} else {
						//Cache data
						cacheDns(dns);
					}
				}
				
				CurrentDomain.insert(name);
				if (update != null) {
					response.sendRedirect("/dns/"+ name);
					return;
				}
			}
		} else {
			response.sendRedirect("/");
			return;
		}
		
		
		ArrayList<String> domains = CurrentDomain.getDomains();
		
		request.setAttribute("dns", dns);
		request.setAttribute("check", check);
		request.setAttribute("title", name +  " - dns record information." );
		request.setAttribute("keywords", keywords);
		request.setAttribute("description", description);
		request.setAttribute("domains", domains);
		try {
			request.getRequestDispatcher("/pages/home.jsp").forward(request, response);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
		}
		
	}
	
	
	private void cacheDns(Dns dns) {
		Cache cache=null;
    	try {
		    cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
		} catch (CacheException e1) {
		   e1.printStackTrace();
		}
		if(cache!=null&&cache.containsKey(dns.getDomain()))
		{
			
		} else {
			cache.put(dns.getDomain(), dns);
		}
	}
}
